import Vue from 'vue'
import VueRouter from 'vue-router'

// 实现路由懒加载
const Login = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Login.vue')
const Home = () => import(/* webpackChunkName: "login_home_welcome" */ '../components/Home.vue')
const Usermanager = () => import('../components/usermanager/Usermanager.vue')
const List = () => import('../components/yuyue/list.vue')
const Details = () => import('../components/yuyue/details.vue')
const Rili = () => import('../components/yuyue/rili.vue')
const Classification = () => import('../components/image/classification.vue')
const Manageimage = () => import('../components/image/manageimage.vue')

const Users = () => import(/* webpackChunkName: "users_rights_roles" */ '../components/user/Users.vue')
const Rights = () => import(/* webpackChunkName: "users_rights_roles" */ '../components/power/Rights.vue')
const Goods = () => import(/* webpackChunkName: "users_rights_roles" */ '../components/goods/index.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/usermanager',
    children: [{ path: '/usermanager', component: Usermanager }, { path: '/yuyue/list', component: List }, { path: '/yuyue/details', component: Details }, { path: '/yuyue/rili', component: Rili }, { path: '/users', component: Users }, { path: '/image/manageimage', component: Manageimage }, { path: '/image/classification', component: Classification }, { path: '/rights', component: Rights }, { path: '/goods', component: Goods }]
  }
]

const router = new VueRouter({
  routes
})

// 挂载路由导航守卫
router.beforeEach((to, from, next) => {
  // to and from are Route Object,next() must be called to resolve the hook}
  // to将要访问的路径 from代表从哪个路径跳转而来
  // next 是一个函数，表示放行 next() 放行 next('/login') 强制跳转到登录页面
  // 如果是登录页，直接放行即可
  if (to.path === '/login') return next()
  // 获取token
  const tokenStr = window.sessionStorage.getItem('token')
  if (!tokenStr) return next('/login')
  next()
})

export default router
